package com.alibaba.aliper.server.controller.servlet;

import java.io.IOException;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.aliper.server.model.domain.Point;
import com.alibaba.aliper.server.model.impl.AliperServer;
import com.alibaba.aliper.server.model.interfaces.AliperView;

/**
 * Servlet implementation class AliperPointer
 */
public class AliperPointer extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AliperPointer() {
		super();
	}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String project = request.getParameter("project");
		String agent = request.getParameter("agent");
		String chart = request.getParameter("chart");
		String line = request.getParameter("line");
		String point = request.getParameter("point");
		if (agent != null && chart != null && line != null && point != null) {
			AliperView view = AliperServer.getAliperServer();
			try {
				Collection<Point> points = view.getAgent(project,agent).getChart(chart)
						.getLine(line).getPointsAfter(Integer.parseInt(point));
				String responseText = "";
				if (points == null) {
					responseText = "null";
				} else {
					for (Point p : points) {
						responseText += p.getX();
						responseText += "@";
						responseText += p.getY();
						responseText += "#";
					}
					if (responseText.endsWith("#")) {
						responseText = responseText.substring(0, responseText
								.length() - 1);
					}
				}
				response.getWriter().write(responseText);
			} catch (NullPointerException e) {
				response
						.getWriter()
						.write(
								"message:please refresh you page to get the latest data");
			} catch (Exception e) {
				response.getWriter().write("message:error" + e);
			}
		}
	}
}
